package com.zhilun.device;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.zhilun.device.entity.*;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.*;
import java.util.stream.Collectors;

public class DeviceBindRequestPushZhiLun {


    //test
//    public static final String key ="ade0ccb442c945fb939a2f82193f6cdf";
//    public static final String secret ="MDEwMzE1MjY2MDVjMWUxOTAxNWM2N2I2OGZiYjJiYzc=";
//    public static final String url = "https://open-p.zhilunkeji.com";


    //pro
    public static final String key ="abc75a7e718a48d29cabe2884dae1d44";
    public static final String secret ="ODY2YmUzZWIwN2Y2ODU0MzIxMGY1NWFkOGQyY2YyMDY=";
    public static final String url = "https://open.zhilunkeji.com";
    public static final String BIND_API ="/open/api/wheels/opt/installSensorNo";
    public static final String UN_BIND_API ="/open/api/wheels/opt/uninstallSensorNo";


    static Map< Integer,String> translationLocation = new HashMap<>();
    static {
        translationLocation.put(1, "L0102");
        translationLocation.put(2, "L0101");
        translationLocation.put(3, "R0101");
        translationLocation.put(4, "R0102");
        translationLocation.put(5, "L0202");
        translationLocation.put(6, "L0201");
        translationLocation.put(7, "R0201");
        translationLocation.put(8, "R0202");
        translationLocation.put(9, "L0302");
        translationLocation.put(10, "L0301");
        translationLocation.put(11, "R0301");
        translationLocation.put(12, "R0302");
        translationLocation.put(97, "L0003");
        translationLocation.put(98, "L0001");
        translationLocation.put(99, "L0002");
    }

    public static void main(String[] args) throws InterruptedException {


        String filePath = "C:\\Users\\hcf\\Desktop\\传感器-大车-需推知轮-1128.xlsx";  // 替换为实际文件路径

        // 读取 Excel 文件
        List<ZhiLunSensorPushParam> dataList = EasyExcel.read(filePath)
                .head(ZhiLunSensorPushParam.class)
                .sheet().headRowNumber(1)
                .doReadSync();
        int count =0;

        String filePath2 = "C:\\Users\\hcf\\Desktop\\传感器-知轮-需推大车-1128.xlsx";  // 替换为实际文件路径

        // 读取 Excel 文件
        List<TireData> zhilunList = EasyExcel.read(filePath2)
                .head(TireData.class)
                .sheet().headRowNumber(1)
                .doReadSync();

        List<String> collect = zhilunList.stream().map(TireData::getSensorId).collect(Collectors.toList());

        ArrayList<String> reList = new ArrayList<>();
        ArrayList<String> errorList = new ArrayList<>();

        for (ZhiLunSensorPushParam data : dataList) {

            if (collect.contains(data.getSensorId())) {
                continue;
            }

            //先解绑
            unSensorBind(data.getSensorId());
            Thread.sleep(100L);

            String location = translationLocation.get(data.getLocation());
            if (location == null) {
                continue;
            }

            if(StrUtil.isBlank(data.getDeviceId()) ||StrUtil.isBlank(data.getLicensePlate())) continue;

            //再绑定
            sensorBind(data.getId(),location, data.getSensorId(),reList,errorList);
            count++;
//            if (count ==1){
//                return;
//            }
            Thread.sleep(500L);
        }

        for (String s : reList) {
            System.out.println(s);
        }

        System.out.println("----------------");


        for (String s : errorList) {
            System.out.println(s);
        }



    }


    public static   void sensorBind(Integer carrierId, String tyrePosition, String sensorNo, ArrayList<String> reList, ArrayList<String> errorList) {
        // 请求参数

        String operator = "黄超凡";




        // 构造签名
        Map<String, String[]> paramMap = new HashMap<>();
        paramMap.put("accessKey", new String[] {key});


        String sign = signParameterMap(paramMap, secret);


        paramMap.put("sign", new String[]{sign});

        // 构造参数Map
        Map<String, Object> param = new HashMap<>();
        param.put("carrierId", carrierId);
        param.put("sensorNo", sensorNo);
        param.put("tyrePosition", tyrePosition);
        param.put("operator", operator);



        // 手动拼接URL和参数
        String fullUrl = url +BIND_API + "?" +sign;



        // 使用Hutool发送GET请求
        HttpRequest request = HttpUtil.createPost(fullUrl).body(JSON.toJSONString(param));

//
        // 执行请求并获取响应
        HttpResponse response = request.execute();

        // 获取响应结果
        String result = response.body();

        System.out.println(result);

        //推送企微群机器人
        JSONObject jsonObject = com.aliyun.openservices.shade.com.alibaba.fastjson.JSON.parseObject(result);
        Integer code = Integer.parseInt(jsonObject.getString("status"));
        String errorMsg = jsonObject.getString("message");
        if (200 != code ) {
            if (code.equals(2040)) {
                reList.add(sensorNo);
                return;
            }
            errorList.add(sensorNo +":  " + result);
        }
    }



    public static   void unSensorBind(String sensorNo) {


        // 请求参数

//        String sensorNo = "22149932"; //浙AP160挂

        String operator = "黄超凡";




        // 构造签名
        Map<String, String[]> paramMap = new HashMap<>();
        paramMap.put("accessKey", new String[] {key});

//        paramMap.put("pageSize", new String[] {pageSize});
        // paramMap.put("alarm", alarm);
        //     paramMap.put("timestamp", new String[] {System.currentTimeMillis() +""});
        String sign = signParameterMap(paramMap, secret);


        paramMap.put("sign", new String[]{sign});

        // 构造参数Map
        Map<String, Object> param = new HashMap<>();

        param.put("sensorNo", sensorNo);
        param.put("operator", operator);



        // 手动拼接URL和参数
        String fullUrl = url +UN_BIND_API + "?" +sign;



        // 使用Hutool发送GET请求
        HttpRequest request = HttpUtil.createPost(fullUrl).body(JSON.toJSONString(param));


        // 执行请求并获取响应
        HttpResponse response = request.execute();

        // 获取响应结果
        String result = response.body();

    }









    public static String signParameterMap(Map<String, String[]> parametersMap, String secret) {
        //添加时间戳，排序并删除空值
        Map<String, String[]> unlock = new HashMap<>(parametersMap);
        unlock.put("timestamp", new String[]{String.valueOf(System.currentTimeMillis() / 1000)});
        List<String> keys = new ArrayList<>(unlock.keySet());
        Collections.sort(keys);
        StringBuilder signStr = new StringBuilder();
        for (String key : keys) {
            String[] values = unlock.get(key);
            if (values.length < 1) {
                continue;
            }
            for (String v : values) {
                signStr.append(key).append("=").append(v).append("&");
            }
        }
        signStr.deleteCharAt(signStr.lastIndexOf("&"));
        String sign = DigestUtils.md5Hex(signStr.toString() + secret);
        signStr.append("&sign=").append(sign);
        return signStr.toString();
    }




}
